package y2016.date1203.pm.古诗文网采集;

import okhttp3.*;
import y2016.date1203.pm.古诗文网采集.Caijier.Holder;

import java.io.IOException;
import java.util.List;

public class HttpString {
    private OkHttpClient okHttpClient;

    public HttpString(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public void writeHtml(List<Holder> holderList, String path, String[] delete, String charset) {
        String newPath = "";
        if (path.endsWith("/")) {
            path = path.substring(path.length() - 2);
        }
        int dotIndex = path.lastIndexOf(".");
        if (dotIndex == -1) {
            newPath = path + "/采集.txt";
        }

        newPath = path.substring(0, dotIndex) + ".txt";

        for (Holder holder : holderList) {
            List<String> urls = holder.getUrls();
            for (String url : urls) {
                String html = getHtmlString(url);
                TextTool.writeFormatToFile(html, delete, path, charset);
            }

        }

    }

    public String getHtmlString(String url) {
        String str = "";
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            str = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!response.isSuccessful()) {
            System.err.println(("服务器端错误: " + response));
        }

//		Headers responseHeaders = response.headers();

        return str;
    }

    public void postHtmlString(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
        String postBody = "Hello World";

        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println("服务器端错误: " + response);
        }

        System.out.println(response.body().string());
    }
}

